package cn.uikit.demo.widget

import android.animation.ValueAnimator
import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.View
import kotlin.math.min

class RingPieChartView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {

    // 数据及颜色（只使用三种颜色）
    private val data = ArrayList<Int>() // 数据比例，必须和100保持一致
    private val colors = listOf(
        Color.parseColor("#ff5d2f"),
        Color.parseColor("#67d298"),
        Color.parseColor("#437fec"),
    )

    private val paint = Paint(Paint.ANTI_ALIAS_FLAG)
    private val textPaint = Paint(Paint.ANTI_ALIAS_FLAG)
    private val rectF = RectF()

    // 动画进度控制
    private var sweepProgress = 0f

    init {
        paint.style = Paint.Style.STROKE
        textPaint.color = Color.BLACK
        textPaint.textSize = 40f
        textPaint.textAlign = Paint.Align.CENTER


    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)

        val width = width.toFloat()
        val height = height.toFloat()
        val radius = min(width, height) / 2 * 0.8f
        val strokeWidth = radius * 0.5f
        paint.strokeWidth = strokeWidth

        // 设置绘制区域
        rectF.set(
            width / 2 - radius,
            height / 2 - radius,
            width / 2 + radius,
            height / 2 + radius
        )

        // 起始角度
        var startAngle = 45f * sweepProgress

        // 绘制每个数据对应的圆弧
        data.forEachIndexed { index, value ->
            // 计算实际绘制角度（包含白色间隔）
            val totalSweepAngle = value / 100f * 360f
            val sweepAngle = totalSweepAngle * sweepProgress // 根据动画进度更新角度
            paint.color = colors[index % colors.size]

            // 绘制彩色部分
            canvas.drawArc(rectF, startAngle, sweepAngle, false, paint)

            // 更新起始角度（保留1%的间隔）
            startAngle += totalSweepAngle
        }
    }

    fun updateData(list:List<Int>) {
        data.clear()
        data.addAll(list)
        val animator = ValueAnimator.ofFloat(0f, 1f)
        animator.duration = 1000 // 动画时长2秒
        animator.addUpdateListener { animation ->
            sweepProgress = animation.animatedValue as Float
            invalidate() // 更新视图
        }
        animator.start()
    }
}
